<template>
  <section class='f-qr-code'>
    <!-- <section class="f-title">
        <img class="f-img1" src="@/assets/icons/icon_shop_head@2x.png" alt="">
        <div>
          <p>{{shopForm.shopName}}</p>
          <p>{{shopForm.shopType == 1? '个人': '企业'}}店铺</p>
        </div>
      </section> -->
    <section id="posterHtml" style="background: #7855e5;padding-bottom:10px">
      <img style="width:100%" src="@/assets/imgs/share_h5_pic1.png" alt="">
      <section class="f-qrcode">
        <qrcode-vue :value="qrUrl" :size="120" level="H" />

        <section class="f-left f-ml-30">
          <p class="f-text1">微信扫一扫</p>
          <p class="f-text2">查看店铺更多精彩</p>
        </section>
      </section>
    </section>

    <section class="f-flex-between f-btn-box">
      <van-button round type="primary" plain style="width:48%" @click="handleCopy()">复制链接</van-button>
      <van-button round type="primary" style="width:48%" @click="downloadPoster()">下载海报</van-button>
    </section>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch, nextTick, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import QrcodeVue from 'qrcode.vue'
import api from '../api'
import { getStore, successDeal } from '@/utils/utils';
import html2canvas from 'html2canvas'
import JsBridge from '@/utils/JsBridge.js'
import { showLoadingToast, closeToast } from 'vant';

export default {
  components: { QrcodeVue },

  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const state = reactive({
      userInfo: {},
      shopForm: {},
      qrUrl: '',
      posterImgURL: "",

      isApp: computed(() => {
        return store.state.isApp
      })
    })

    onMounted(() => {
      state.userInfo = getStore('USER_INFO_MF')

      store.commit("setNavBar", {
        title: '分享店铺',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightType: 'search',
      });

      getShopInfo()
    })

    const getShopInfo = () => {
      api.shopInfo().then(res => {
        state.shopForm = res.data
        state.qrUrl = getUrl()

        createPoster()
      })
    }

    const getUrl = () => {
      let url = ``
      let shopName = encodeURI(state.shopForm.shopName)
      if (WEB_SOURCE.mode == "master") {
        url = `https://miaofanbao.yilianyun.top/manager/#/h5?m=${state.shopForm.shopId}&u=${state.userInfo.userId}&n=${shopName}`
      } else {
        url = `http://192.168.10.31:5001/miaofan_web/#/h5?m=${state.shopForm.shopId}&u=${state.userInfo.userId}&n=${shopName}`
      }
      return url
    }

    function handleCopy(value) {
      const input = document.createElement('input');
      document.body.appendChild(input)

      let url = getUrl(value)
      input.setAttribute('value', url);
      input.select();
      if (document.execCommand('copy')) {
        document.execCommand('copy');
        successDeal('复制成功！')
      }
      document.body.removeChild(input);
    }

    // 生成海报
    const createPoster = () => {
      nextTick(() => {
        let posterDOM = document.getElementById('posterHtml')

        html2canvas(posterDOM, {
          width: posterDOM.offsetWidth,
          height: posterDOM.offsetHeight,
          //按比例增加分辨率
          scale: window.devicePixelRatio, // 设备像素比
          useCORS: true,//（图片跨域相关）
          allowTaint: true,//允许跨域（图片跨域相关）
          logging: false,
          letterRendering: true,
        }).then(function (canvas) {
          state.posterImgURL = canvas.toDataURL('image/png')
        })
      })
    }

    // 下载海报
    const downloadPoster = (base64, fileName) => {
      showLoadingToast({
        message: '保存中...',
        forbidClick: true,
        duration: 0,
      });

      if (state.isApp) {
        JsBridge.callHandler('saveFileByBase64', { base64: state.posterImgURL, fileName: '秒返宝.png' }, (res) => {
          let success = JSON.parse(res).success
          if (success) {
            successDeal('保存成功，请前往相册查看！')
          } else {
            successDeal('保存失败')
          }
        })
      } else {
        saveImg(base64ToUrl(state.posterImgURL), '秒返宝.png')
        closeToast()
      }
    }

    function base64ToUrl(imgdata) {
      let base = imgdata
      if (imgdata.indexOf('data:image/png;base64' > -1)) {
        base = imgdata.split(",")[1]
      }
      const byteCharacters = atob(base)
      const byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)
      const blob = new Blob([byteArray], { type: "image/jpeg" })
      let binaryData = []
      binaryData.push(blob)
      let url = URL.createObjectURL(new Blob(binaryData))
      return url
    }

    function saveImg(url, fileName) {
      const a = document.createElement('a')
      a.setAttribute('download', fileName)
      a.href = url
      a.click()
    }

    const test = () => {
      var base64String = "..."; // 这里是你的 Base64 图片字符串
      var img = new Image();
      img.src = state.posterImgURL;
      console.log(state.posterImgURL)
      document.getElementById('f-test').appendChild(img);
    }

    return {
      ...toRefs(state),
      handleCopy,
      downloadPoster,
      test
    }
  }
}
</script>
<style lang='scss' scoped>
.f-qr-code {
  position: relative;
  background: #7855e5 !important;
  // border: 1px solid red;
  padding-bottom: 200px;
  .f-title {
    display: flex;
    .f-img1 {
      width: 54px;
      height: 54px;
      margin-right: 9px;
    }
    p:first-child {
      font-size: 20px;
      font-weight: 500;
      color: #000000;
    }
    p:last-child {
      font-size: 14px;
      color: #666666;
      margin-top: 10px;
    }
  }
  .f-qrcode {
    text-align: center;
    display: flex;
    align-items: center;
    padding-left: 50px;
  }
  .f-text1 {
    font-size: 14px;
    color: #fff;

    margin-top: 16px;
    margin-bottom: 12px;
  }
  .f-text2 {
    font-size: 12px;
    color: #fff;
  }
  .f-btn-box {
    padding: 20px;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
  }
}
</style>